﻿@page "/add"

@inject IDbContextFactory<ContactContext> DbFactory
@inject NavigationManager Navigation
@inject IPageHelper PageHelper

@if (Contact is not null)
{
    <ContactForm Busy="Busy" 
                   Contact="Contact" 
                   IsAdd="true"
                   CancelRequest="Cancel"
                   ValidationResult="@(async (success) => await ValidationResultAsync(success))" />
}
@if (Success)
{
    <br />
    <div class="alert alert-success">The contact was successfully added.</div>
}
@if (Error)
{
    <br />
    <div class="alert alert-danger">Failed to add the contact (@ErrorMessage).</div>
}

@code {
    /// <summary>
    /// New <see cref="Contact"/>.
    /// </summary>
    private Contact? Contact { get; set; }

    /// <summary>
    /// <c>True</c> when an asynchronous operation is running.
    /// </summary>
    private bool Busy;

    /// <summary>
    /// <c>True</c> after successful add.
    /// </summary>
    private bool Success;

    /// <summary>
    /// <c>True</c> when an error occurred.
    /// </summary>
    private bool Error;

    /// <summary>
    /// The error message
    /// </summary>
    private string ErrorMessage = string.Empty;

    /// <summary>
    /// Start with fresh <see cref="Contact"/>.
    /// </summary>
    /// <returns>A <see cref="Task"/>.</returns>
    protected override Task OnInitializedAsync()
    {
        Contact = new();
        return base.OnInitializedAsync();
    }

    /// <summary>
    /// Respond to a forms submission.
    /// </summary>
    /// <param name="success"><c>True</c> when valid.</param>
    /// <returns>A <see cref="Task"/>.</returns>
    private async Task ValidationResultAsync(bool success)
    {
        if (Busy)
        {
            return;
        }

        if (!success)
        {
            Success = false;
            Error = false;
            return;
        }

        Busy = true;

        using var context = DbFactory.CreateDbContext();

        // this just attaches
        if (Contact is not null)
        {
            context.Contacts?.Add(Contact);
        }

        try
        {
            await context.SaveChangesAsync();
            Success = true;
            Error = false;
            // ready for the next
            Contact = new();
            Busy = false;
        }
        catch (Exception ex)
        {
            Success = false;
            Error = true;
            ErrorMessage = ex.Message;
            Busy = false;
        }
    }

    /// <summary>
    /// Back to list.
    /// </summary>
    private void Cancel()
    {
        Navigation.NavigateTo($"/{PageHelper.Page}");
    }
}
